<template>
  <div class="taobao-management-view">
    <!-- 筛选区和设置图标同一行 -->
    <div class="filter-bar">
      <div class="filter-area">
        <el-input
          v-model="searchQuery"
          placeholder="店铺名称/商品名称"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 200px; margin-left: 10px; --el-input-bg-color: #f5f7fa;"
        ></el-input>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleAdd">新增店铺</el-button>
      </div>
      <div class="filter-setting-icon">
        <el-popover
          placement="bottom-end"
          width="200"
          trigger="click"
          v-model="showColumnSetting"
        >
          <div v-for="col in columns" :key="col.key" v-if="col.key !== 'selection' ">
            <el-checkbox v-model="col.visible">{{ col.label }}</el-checkbox>
          </div>
          <div style="text-align: right;">
            <el-button type="text" size="mini" @click="resetColumns">重置</el-button>
          </div>
          <i
            class="el-icon-setting"
            slot="reference"
            style="cursor: pointer; font-size: 20px; margin-left: 10px;"
          ></i>
        </el-popover>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table ref="taobaoTable" :data="taobaoData" style="width: 100%; margin-top: 20px;" border @selection-change="handleSelectionChange">
      <el-table-column v-if="getColumnVisible('selection')" type="selection" width="40"></el-table-column>
      <el-table-column v-if="getColumnVisible('index')" label="序号" width="60">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
     
      <el-table-column v-if="getColumnVisible('shop_name')" prop="shop_name" label="店铺名称" min-width="150"></el-table-column>
      <el-table-column v-if="getColumnVisible('product_name')" prop="product_name" label="商品名称" min-width="200"></el-table-column>
      <el-table-column v-if="getColumnVisible('shop_img')" prop="shop_img" label="商品图片" width="120" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="getFirstImage(scope.row.shop_img)"
            :src="getFirstImage(scope.row.shop_img)"
            :preview-src-list="getImageList(scope.row.shop_img)"
            style="width: 60px; height: 60px;"
            fit="cover"
          ></el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column v-if="getColumnVisible('shop_url')" prop="shop_url" label="店铺链接" min-width="200">
        <template slot-scope="scope">
          <el-link :href="scope.row.shop_url" target="_blank" type="primary" v-if="scope.row.shop_url">
            {{ truncateUrl(scope.row.shop_url) }}
          </el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column v-if="getColumnVisible('amount')" prop="amount" label="价格" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.amount ? '¥' + scope.row.amount : '-' }}
        </template>
      </el-table-column>
      <el-table-column v-if="getColumnVisible('status')" prop="status" label="状态" width="200" align="center">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
            <span class="status-button" :class="getStatusButtonClass(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </span>
            <el-dropdown trigger="click" @command="(command) => handleStatusChange({ id: scope.row.id, status: parseInt(command) })">
              <el-button icon="el-icon-edit" size="mini" circle style="padding: 0; width: 24px; height: 24px;"></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="1" :disabled="scope.row.status == 1">
                  <span style="color: #67C23A;">✓ 正常</span>
                </el-dropdown-item>
                <el-dropdown-item :command="2" :disabled="scope.row.status == 2">
                  <span style="color: #409EFF;">✓ 置顶</span>
                </el-dropdown-item>
                <el-dropdown-item :command="3" :disabled="scope.row.status == 3">
                  <span style="color: #F56C6C;">✓ 禁用</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="getColumnVisible('create_time')" prop="create_time" label="创建时间" min-width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column v-if="getColumnVisible('operate')" label="操作" width="200" align="center" fixed="right">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container" style="text-align: right; margin-top: 10px;">
      <PageCom :total="total" :pageSize="pageSize" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></PageCom>
    </div>

    <!-- 添加/编辑店铺弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="shop_name">
              <el-input v-model="form.shop_name" placeholder="请输入店铺名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="product_name">
              <el-input v-model="form.product_name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="店铺链接" prop="shop_url">
              <el-input v-model="form.shop_url" placeholder="请输入店铺链接"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="amount">
              <el-input-number v-model="form.amount" :min="0" :precision="2" placeholder="请输入价格" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
         <el-form-item label="商品图片" prop="shop_img">
           <el-upload
             ref="upload"
             :file-list="fileList"
             :http-request="customUpload"
             :on-remove="handleRemove"
             :before-upload="beforeUpload"
             list-type="picture-card"
             :limit="5"
             :on-exceed="handleExceed"
             :auto-upload="true"
             :show-file-list="true"
             :on-preview="handlePreview"
             :on-change="handleFileChange"
           >
             <i class="el-icon-plus"></i>
           </el-upload>
           <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB，最多5张。选择图片后立即上传</div>
         </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="1"></el-option>
            <el-option label="置顶" value="2"></el-option>
            <el-option label="禁用" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看店铺详情弹窗 -->
    <el-dialog
      title="店铺详情"
      :visible.sync="viewDialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="管理员姓名">{{ viewData.admin?.adminName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="管理员手机号">{{ viewData.admin?.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="商户号">{{ viewData.admin?.merchantNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="店铺名称">{{ viewData.shop_name }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ viewData.product_name }}</el-descriptions-item>
        <el-descriptions-item label="店铺链接">
          <el-link :href="viewData.shop_url" target="_blank" type="primary" v-if="viewData.shop_url">
            {{ viewData.shop_url }}
          </el-link>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="价格">{{ viewData.amount ? '¥' + viewData.amount : '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTag(viewData.status)" :class="getStatusClass(viewData.status)">
            {{ getStatusText(viewData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商品图片" v-if="getImageList(viewData.shop_img).length > 0">
          <el-image
            v-for="(img, index) in getImageList(viewData.shop_img)"
            :key="index"
            :src="img"
            style="width: 80px; height: 80px; margin-right: 10px; margin-bottom: 10px;"
            fit="cover"
            :preview-src-list="getImageList(viewData.shop_img)"
          ></el-image>
        </el-descriptions-item>
        <el-descriptions-item label="商品描述">{{ viewData.description || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(viewData.create_time) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import PageCom from '@/components/PageCom.vue';
import { getTaobaoList, taobaoAdd, taobaoEdit, taobaoDelete, uploadImage, taobaoChangeStatus } from '@/api/contract';

export default {
  name: 'TaobaoManagementView',
  components: {
    PageCom,
  },
  data() {
    return {
      dateRange: '',
      searchQuery: '',
      taobaoData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      selectedTaobao: [], // 存储选中的店铺
      // 弹窗相关数据
      dialogVisible: false,
      submitLoading: false,
      dialogTitle: '添加店铺',
      isEdit: false,
      form: {
        id: null,
        shop_name: '',
        product_name: '',
        shop_url: '',
        amount: 0,
        shop_img: [],
        description: '',
        status: '1'
      },
      rules: {
        shop_name: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' }
        ],
        product_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        shop_url: [
          { required: true, message: '请输入店铺链接', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      // 文件上传相关
      fileList: [],
      // 查看详情相关
      viewDialogVisible: false,
      viewData: {},
      // 字段显示控制配置
      columns: [
        { key: 'selection', label: '', visible: true },
        { key: 'index', label: '序号', visible: true },
        { key: 'adminName', label: '管理员姓名', visible: true },
        { key: 'adminPhone', label: '管理员手机号', visible: true },
        { key: 'merchantNo', label: '商户号', visible: true },
        { key: 'shop_name', label: '店铺名称', visible: true },
        { key: 'product_name', label: '商品名称', visible: true },
        { key: 'shop_img', label: '商品图片', visible: true },
        { key: 'shop_url', label: '店铺链接', visible: true },
        { key: 'amount', label: '价格', visible: true },
        { key: 'status', label: '状态', visible: true },
        { key: 'create_time', label: '创建时间', visible: true },
        { key: 'operate', label: '操作', visible: true }
      ],
      showColumnSetting: false,
    };
  },
  methods: {
    formatDate(timestamp) {
      if (!timestamp) return '-';
      
      console.log('格式化时间戳:', timestamp, '类型:', typeof timestamp);
      
      // 处理不同的时间戳格式
      let date;
      if (typeof timestamp === 'string') {
        // 如果是字符串，尝试直接解析
        date = new Date(timestamp);
      } else if (timestamp.toString().length === 10) {
        // 如果是10位时间戳（秒），转换为毫秒
        date = new Date(timestamp * 1000);
      } else if (timestamp.toString().length === 13) {
        // 如果是13位时间戳（毫秒），直接使用
        date = new Date(timestamp);
      } else {
        // 其他情况，尝试直接解析
        date = new Date(timestamp);
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('无效的时间戳:', timestamp);
        return '-';
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 获取状态标签样式
    getStatusTag(status) {
      const statusMap = {
        '1': 'success',  // 正常 - 绿色
        '2': '',         // 置顶 - 使用自定义蓝色（不设置type）
        '3': 'danger'    // 禁用 - 红色
      };
      return statusMap[status] || 'info';
    },
    // 获取状态自定义类名
    getStatusClass(status) {
      return status === '2' ? 'status-top' : '';
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '1': '正常',
        '2': '置顶',
        '3': '禁用'
      };
      return statusMap[status] || '未知';
    },
    // 获取状态按钮样式类
    getStatusButtonClass(status) {
      const statusClassMap = {
        '1': 'status-button-normal',
        '2': 'status-button-top',
        '3': 'status-button-disabled'
      };
      return statusClassMap[status] || '';
    },
    // 获取第一张图片
    getFirstImage(shopImg) {
      if (!shopImg) return '';
      const images = shopImg.split(';');
      const firstImg = images[0] || '';
      return this.getFullImageUrl(firstImg);
    },
    // 获取图片列表
    getImageList(shopImg) {
      if (!shopImg) return [];
      const images = shopImg.split(';').filter(img => img.trim());
      return images.map(img => this.getFullImageUrl(img));
    },
    // 获取完整的图片URL
    getFullImageUrl(imagePath) {
      if (!imagePath) return '';
      
      console.log('处理图片路径:', imagePath);
      
      // 如果已经是完整URL，直接返回
      if (imagePath.startsWith('http')) {
        console.log('已经是完整URL:', imagePath);
        return imagePath;
      }
      
      // 确保路径以 / 开头
      const normalizedPath = imagePath.startsWith('/') ? imagePath : `/${imagePath}`;
      
      // 拼接基础路径
      const baseUrl = 'http://101.pay123.shop/';
      const fullUrl = `${baseUrl}${normalizedPath}`;
      
      console.log('拼接后的完整URL:', fullUrl);
      
      return fullUrl;
    },
    // 截断URL显示
    truncateUrl(url) {
      if (!url) return '-';
      return url.length > 30 ? url.substring(0, 30) + '...' : url;
    },
    // 获取店铺列表数据
    async fetchTaobaoList() {
      try {
        console.log('开始获取淘宝店铺列表数据...');
        // 处理时间范围
        let timeParams = [];
        if (this.dateRange && this.dateRange.length === 2) {
          // 将日期转换为时间戳（秒）
          timeParams = [
            Math.floor(this.dateRange[0].getTime() / 1000),
            Math.floor(this.dateRange[1].getTime() / 1000)
          ];
        }

        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery || '',
          time: timeParams
        };
        
        console.log('请求参数:', params);
        const res = await getTaobaoList(params);
        console.log('API响应:', res);
        
        if (!res) {
          this.$message.error('服务器响应为空');
          return;
        }

        if (res.data && res.data.code === 200) {
          const { data } = res;
          
          if (!data || !data.data || data.data.length === 0) {
            this.taobaoData = [];
            this.total = 0;
            this.$message.info(res.data.msg || '暂无数据');
            return;
          }

          // 直接使用后端返回的数据
          this.taobaoData = res.data.data.data || [];
          this.total = res.data.data.total || 0;
          this.currentPage = res.data.data.current_page || 1;

        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('获取店铺列表失败:', error);
        console.error('错误详情:', error.message);
        console.error('错误堆栈:', error.stack);
        this.$message.error('获取店铺列表失败: ' + error.message);
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchTaobaoList();
    },
    resetSearch() {
      this.searchQuery = '';
      this.dateRange = '';
      this.currentPage = 1;
      this.fetchTaobaoList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchTaobaoList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTaobaoList();
    },
    handleAdd() {
      this.isEdit = false;
      this.dialogTitle = '添加店铺';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.resetForm();
      });
    },
    handleEdit(row) {
      this.isEdit = true;
      this.dialogTitle = '编辑店铺';
      
      console.log('编辑数据:', row);
      
      // 处理图片数据
      let shopImgArray = [];
      if (row.shop_img) {
        const images = row.shop_img.split(';');
        shopImgArray = images.filter(img => img.trim());
      }
      
      console.log('图片数组:', shopImgArray);
      
      // 填充表单数据
      this.form = {
        id: row.id,
        shop_name: row.shop_name,
        product_name: row.product_name,
        shop_url: row.shop_url,
        amount: row.amount,
        shop_img: shopImgArray, // 使用相对路径数组
        description: row.description || '',
        status: row.status.toString()
      };
      
      // 处理图片文件列表（用于显示）
      this.fileList = [];
      if (row.shop_img) {
        const images = row.shop_img.split(';');
        images.forEach((img, index) => {
          if (img.trim()) {
            const fullUrl = this.getFullImageUrl(img.trim());
            console.log(`图片 ${index}:`, img.trim(), '->', fullUrl);
            this.fileList.push({
              name: `image_${index}.jpg`,
              url: fullUrl,
              status: 'success' // 确保状态为成功
            });
          }
        });
      }
      
      console.log('最终文件列表:', this.fileList);
      
      // 测试图片URL是否可访问
      this.fileList.forEach((file, index) => {
        console.log(`测试图片 ${index} URL:`, file.url);
        // 创建一个测试图片元素来验证URL
        const testImg = new Image();
        testImg.onload = () => {
          console.log(`图片 ${index} 加载成功:`, file.url);
        };
        testImg.onerror = () => {
          console.error(`图片 ${index} 加载失败:`, file.url);
        };
        testImg.src = file.url;
      });
      
      console.log('表单数据:', this.form);
      console.log('文件列表:', this.fileList);
      
      this.dialogVisible = true;
    },
    handleView(row) {
      this.viewData = { ...row };
      this.viewDialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('确认要删除该店铺吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await taobaoDelete(row.id);
          if (response.data.code === 200) {
            this.$message.success('删除成功');
            this.fetchTaobaoList(); // 刷新列表
          } else {
            this.$message.error(response.data.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除店铺失败:', error);
          this.$message.error('删除失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleStatusChange(row) {
      const statusTextMap = {
        1: '正常',
        2: '置顶',
        3: '禁用'
      };
      this.$confirm(`确认要将该店铺状态修改为"${statusTextMap[row.status]}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await taobaoChangeStatus(row.id, row.status);
          if (response.data.code === 200) {
            this.$message.success(response.data.msg);
            // 刷新列表
            this.fetchTaobaoList();
          } else {
            this.$message.error(response.data.msg || '状态修改失败');
            // 恢复原状态
            this.fetchTaobaoList();
          }
        } catch (error) {
          console.error('状态修改失败:', error);
          this.$message.error('状态修改失败，请稍后重试');
          // 恢复原状态
          this.fetchTaobaoList();
        }
      }).catch(() => {
        // 取消操作，恢复原状态
        this.fetchTaobaoList();
        this.$message.info('已取消操作');
      });
    },
    handleCancel() {
      this.dialogVisible = false;
      this.resetForm();
    },
    resetForm() {
      this.form = {
        id: null,
        shop_name: '',
        product_name: '',
        shop_url: '',
        amount: 0,
        shop_img: [],
        description: '',
        status: '1'
      };
      this.fileList = [];
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    // 文件上传相关方法
    beforeUpload(file) {
      console.log('beforeUpload 检查文件:', file.name, file.type, file.size);
      
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      
      console.log('文件验证通过，允许上传');
      return true;
    },
    // 自定义上传方法
    async customUpload(options) {
      console.log('=== customUpload 被调用 ===');
      console.log('上传选项:', options);
      
      const { file } = options;
      const { onSuccess, onError } = options;
      
      try {
        console.log('开始上传图片:', file.name, file.type, file.size);
        console.log('上传前图片数组:', this.form.shop_img);
        
        // 显示上传进度
        this.$message.info('正在上传图片...');
        
        const response = await uploadImage(file);
        console.log('上传响应:', response);
        
        if (response.data.code === 200) {
          // 将返回的相对路径添加到图片数组中
          const imagePath = response.data.path;
          this.form.shop_img.push(imagePath);
          console.log('上传后图片数组:', this.form.shop_img);
          
          // 构造上传成功的响应数据
          const successResponse = {
            url: this.getFullImageUrl(imagePath),
            name: file.name,
            status: 'success'
          };
          
          console.log('构造的成功响应:', successResponse);
          
          // 通知上传组件上传成功
          onSuccess(successResponse, file);
          this.$message.success('图片上传成功');
        } else {
          console.error('上传失败，响应码:', response.data.code);
          this.$message.error(response.data.msg || '图片上传失败');
          onError(new Error(response.data.msg || '图片上传失败'));
        }
      } catch (error) {
        console.error('图片上传失败:', error);
        this.$message.error('图片上传失败: ' + error.message);
        onError(error);
      }
    },
    handleRemove(file, fileList) {
      console.log('删除图片:', file);
      console.log('删除前图片数组:', this.form.shop_img);
      
      // 获取要删除的图片路径
      const fileUrl = file.url;
      console.log('要删除的图片URL:', fileUrl);
      
      // 在form.shop_img中查找并删除对应的路径
      let foundIndex = -1;
      
      // 遍历图片数组，查找匹配的路径
      for (let i = 0; i < this.form.shop_img.length; i++) {
        const imgPath = this.form.shop_img[i];
        const fullImgUrl = this.getFullImageUrl(imgPath);
        
        // 匹配完整URL或相对路径
        if (fullImgUrl === fileUrl || imgPath === fileUrl) {
          foundIndex = i;
          break;
        }
      }
      
      if (foundIndex > -1) {
        // 从数组中删除找到的图片
        this.form.shop_img.splice(foundIndex, 1);
        console.log('删除后图片数组:', this.form.shop_img);
        this.$message.success('图片删除成功');
      } else {
        console.warn('未找到要删除的图片路径');
        this.$message.warning('删除失败：未找到对应的图片');
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 5 张图片，当前选择了 ${files.length} 张，共选择了 ${files.length + fileList.length} 张`);
    },
    handlePreview(file) {
      console.log('预览图片:', file);
    },
    handleFileChange(file, fileList) {
      console.log('文件变化:', file, fileList);
      console.log('当前文件列表长度:', fileList.length);
    },
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
        try {
          const submitData = { ...this.form };
          console.log('提交前表单数据:', submitData);
          
          // 将图片数组转换为分号分隔的字符串
          if (submitData.shop_img && Array.isArray(submitData.shop_img)) {
            submitData.shop_img = submitData.shop_img.join(';');
            console.log('转换后的图片字符串:', submitData.shop_img);
          }
            
            let response;
            if (this.isEdit) {
              response = await taobaoEdit(submitData);
            } else {
              response = await taobaoAdd(submitData);
            }
            
            // 处理响应
            if (response.data.code === 200) {
              this.$message.success(response.data.msg || (this.isEdit ? '更新成功' : '添加成功'));
              this.dialogVisible = false;
              this.fetchTaobaoList(); // 刷新列表
            } else {
              this.$message.error(response.data.msg || (this.isEdit ? '更新失败' : '添加失败'));
            }
          } catch (error) {
            // 处理业务错误
            if (error.handled) {
              this.$message.error(error.message || '操作失败');
            } else {
              console.error('提交失败:', error);
              this.$message.error('操作失败，请稍后重试');
            }
          } finally {
            this.submitLoading = false;
          }
        }
      });
    },
    handleSelectionChange(selection) {
      this.selectedTaobao = selection;
    },
    getColumnVisible(key) {
      const col = this.columns.find(c => c.key === key);
      return col ? col.visible : false;
    },
    resetColumns() {
      this.columns.forEach(col => col.visible = true);
    },
   },
   created() {
     console.log('=== TaobaoManagementView 组件已创建 ===');
     console.log('当前路由:', this.$route.path);
     console.log('开始调用 fetchTaobaoList...');
     try {
       this.fetchTaobaoList();
     } catch (error) {
       console.error('创建时调用 fetchTaobaoList 失败:', error);
     }
   },
   mounted() {
     console.log('TaobaoManagementView 组件已挂载');
     console.log('组件挂载完成，检查数据:', this.taobaoData);
   }
 };
</script>

<style scoped>
.taobao-management-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
  width: 100%;
  max-width: none;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-area {
  display: flex;
  align-items: center;
}

.filter-setting-icon {
  display: flex;
  align-items: center;
  height: 32px;
}

/* 表格样式调整 */
.el-table {
  border: 1px solid #EBEEF5;
  width: 100% !important;
  table-layout: auto;
}

.el-table th {
  background-color: #566275 !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}

>>> .el-table th.el-table__cell {
  background-color: #f5f7fa !important; /* Element UI 默认的表头背景色 */
}
.el-table::after, .el-table::before {
  background-color: transparent;
}

/* 确保表格占满容器宽度 */
::v-deep .el-table {
  width: 100% !important;
}

::v-deep .el-table__body-wrapper {
  width: 100% !important;
}

::v-deep .el-table__header-wrapper {
  width: 100% !important;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.dialog-footer {
  text-align: right;
}

::v-deep .el-input__inner {
  background-color: white !important;
}

/* 图片预览样式 */
.el-image {
  border-radius: 4px;
  cursor: pointer;
}

/* 上传组件样式 */
::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}

/* 状态标签自定义样式 */
.status-top {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}
.status-top:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 状态按钮样式 */
.status-button {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  border: 1px solid;
  white-space: nowrap;
}

/* 正常 - 绿色 */
.status-button-normal {
  background-color: #f0f9ff;
  border-color: #67C23A;
  color: #67C23A;
}

/* 置顶 - 蓝色 */
.status-button-top {
  background-color: #ecf5ff;
  border-color: #409EFF;
  color: #409EFF;
}

/* 禁用 - 红色 */
.status-button-disabled {
  background-color: #fef0f0;
  border-color: #F56C6C;
  color: #F56C6C;
}
</style>
